import React,{useCallback,useRef,UIEvent} from "react";



interface  Position {
    x:number,
    y:number
}

interface GestureState {
  move:[x:number,y:number],  // 移动时的坐标位置
  moving:boolean,   // 是否处于移动中 
  dir:[x:-1| 1,y: -1 | 1],  // x与y轴移动的方向 
  drag:boolean  // 是否拖拽 需要通过判断拖拽的距离来

}
interface GestureCallback {
  (state:GestureState,target:UIEvent):number
}

export default function useGesture(callback) {
    const startRef = useRef<Position | null>(null);
    const stateRef = useRef<GestureState | null>(null)
    const callBackRef = useRef<GestureCallback | null>(null)
    callBackRef.current = callback;
    const  _onStart =useCallback((target)=>{
        if(target){
            startRef.current={
                x:target.pageX,
                y:target.pageY
            }
        }         
     },[])
     const _onMove = useCallback((target,touchTarget)=>{
        
         if(startRef.current){
            const x = target.pageX - startRef.current.x;
            const y = target.pageY - startRef.current.y;
            // console.log('x',x);
           // 判断移动的方向, 移动的坐标位置,
           stateRef.current ={
               move:[x,y],
               moving:true,
               dir:[x>=0?1:-1,y>=0?1:-1],
               drag:false
           }
         }
         callBackRef?.current(stateRef.current,touchTarget);
     },[])
    const _onEnd =useCallback((_,target)=>{
        if(startRef.current&&stateRef.current){
            stateRef.current.moving=false;
            callBackRef?.current(stateRef.current,target)
        }
         startRef.current= null;
         stateRef.current=null;

    },[])

 
 return {
    onTouchStart(e){
        // console.log('touchStart',e);
        e.stopPropagation()
        _onStart(e.changedTouches[0]);
       
    },
    onTouchMove(e){
        e.stopPropagation();
        _onMove(e.changedTouches[0],e);
       
    },
    onTouchEnd(e){
        e.stopPropagation();
        _onEnd(e,e);
       
    },
    onMouseDown(e){
        e.stopPropagation();
       _onStart(e.changedTouches[0]);
    },
    onMouseMove(e){
        console.log('mouseMove',e);
        e.stopPropagation();
        _onMove(e,e);
    },
    onMouseUp(e){
        e.stopPropagation();
        _onEnd(e.changedTouches[0],e);
    },
    onMouseLeave(e){
        e.stopPropagation();
        _onEnd(e,e);
    }


    
 }
}


